#include "usart.h"
void usart_init(void)
{
    //1.配置时钟
    RCC->APB2ENR|=RCC_APB2ENR_IOPAEN;  //开启时钟
    RCC->APB2ENR |=RCC_APB2ENR_USART1EN;//开启复用功能的时钟
    //2.端口的配置  输出TX 接收RE  PA9 TX推挽输出CNY 10 MODE 11     PA10 RX浮空输入CNY 01 MODE00
    GPIOA->CRH |=GPIO_CRH_MODE9;
    GPIOA->CRH |=GPIO_CRH_CNF9_1;
    GPIOA->CRH &=~GPIO_CRH_CNF9_0;

    GPIOA->CRH &=~GPIO_CRH_MODE10;
    GPIOA->CRH |=GPIO_CRH_CNF10_0;
    GPIOA->CRH &=~GPIO_CRH_CNF10_1;
    //3.配置usart 波特率 数据位 停止位
    USART1->BRR=0x271;
	
	
    //数据帧格式
    USART1->CR1|=(USART_CR1_RE|USART_CR1_TE|USART_CR1_UE);
    USART1->CR1&=~USART_CR1_M;
    USART1->CR1&=~USART_CR1_PCE;
    USART1->CR2&=~USART_CR2_STOP;
}

void usart_send(uint8_t ch)
{
   while((USART1->SR & USART_SR_TXE)==0)
   {

   }
   USART1->DR=ch;
}

uint8_t usart_receive(void)
{
    while ((USART1->SR & USART_SR_RXNE)==0)
    {
        if(USART1->SR & USART_SR_IDLE)
        {
            return 0;
        }
    }
    return USART1->DR;
}

void usart_sendchars(uint8_t *ch,uint8_t size)
{
    int a;
    for(a=0;a<size;a++)
    {
        usart_send(ch[a]);
    }
}

 void usart_Receivechars(uint8_t *ch,uint8_t *size)        //最后的优化版
{
    uint8_t i=0;
        while ((USART1->SR & USART_SR_IDLE)==0)
        {
           ch[i]=usart_receive();
           i++;
        }
        USART1->DR;
       *size=--i;
}

int fputc(int data, FILE * file)
{
    usart_send(data);
}
